document.addEventListener('DOMContentLoaded', function() {
    loadCategories();
    const uploadForm = document.getElementById('upload-form');
    uploadForm.addEventListener('submit', function(event) {
        event.preventDefault();
        uploadArticle();
    });
});

function loadCategories() {
    fetch('/blog/text/listType')
        .then(response => response.json())
        .then(data => {
            if (data.code === 1) {
                const typeSelect = document.getElementById('type');
                data.data.forEach(category => {
                    const option = document.createElement('option');
                    option.value = category;
                    option.textContent = category;
                    typeSelect.appendChild(option);
                });
            } else {
                alert('加载分类失败：' + data.msg);
            }
        })
        .catch(error => {
            alert('请求失败：' + error.message);
        });
}

function uploadArticle() {
    const title = document.getElementById('title').value;
    const content = document.getElementById('content').value;
    const type = document.getElementById('type').value;

    fetch('/blog/user/upload', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ title, content, type })
    })
        .then(response => response.json())
        .then(data => {
            const uploadResponse = document.getElementById('upload-response');
            if (data.code === 1) {
                uploadResponse.textContent = '上传成功';
                uploadResponse.style.color = 'green';
            } else {
                uploadResponse.textContent = '上传失败：' + data.msg;
                uploadResponse.style.color = 'red';
            }
        })
        .catch(error => {
            const uploadResponse = document.getElementById('upload-response');
            uploadResponse.textContent = '请求失败：' + error.message;
            uploadResponse.style.color = 'red';
        });
}

